package com.zj.job;

import com.zj.bean.CommonConfig;
import com.zj.bean.TableColumnInfo;
import com.zj.bean.TableInfo;
import com.zj.controller.CommonCtl;
import com.zj.data.DataCenter;
import javafx.application.Platform;
import org.apache.commons.lang.StringUtils;
import com.zj.processors.CommonProcessor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CommonJob extends Thread{

    private static final String DRIVER = "com.mysql.jdbc.Driver";

    private CommonConfig config;
    private CommonCtl controller;
    private CommonProcessor processor;

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public CommonJob(CommonCtl controller, CommonProcessor processor) {
        this.config=DataCenter.getData("commonConfig", CommonConfig.class);
        this.controller=controller;
        this.processor=processor;
    }


    public CommonConfig getConfig() {
        return config;
    }

    @Override
    public void run(){
        List<String> tableList=new ArrayList();
        getTableList(tableList,processor.getParam("tableName"));
        if(tableList.size()==0){
//            sendChat("wrong param, example:\n code table1 table2 ...");
            return;
        }
        generate(tableList);
        log("任务执行完成");
    }

    public static List<TableColumnInfo> getFieldMap(String tableName,Connection connection) throws SQLException {
        List<TableColumnInfo> columnList=new ArrayList<>();
//        String sql="desc "+tableName;
        String sql="show full columns from "+tableName;

        ResultSet result=doQuery(sql,connection);
        while(result.next()) {
            TableColumnInfo tableColumnInfo=new TableColumnInfo();
            tableColumnInfo.setName(result.getString("Field"));
            tableColumnInfo.setType(result.getString("Type"));
            tableColumnInfo.setComment(result.getString("Comment"));
            if(StringUtils.isEmpty(tableColumnInfo.getComment()) && tableColumnInfo.getName()!=null){
                if(tableColumnInfo.getName().equals("is_delete")){
                    continue;
                }
                if(tableColumnInfo.getName().equals("org_id")){
                    continue;
                }
                if(tableColumnInfo.getName().equals("create_time")){
                    continue;
                }
                if(tableColumnInfo.getName().equals("update_time")){
                    continue;
                }
            }

            columnList.add(tableColumnInfo);
        }
        return columnList;
    }


    public static ResultSet doQuery(String sql,Connection connection) throws SQLException {
        Statement sta1 = connection.createStatement();
        return sta1.executeQuery(sql);
    }

    public boolean generate(List<String> tableList){
        log("start generate MBG obj");
        List<String> warnings = new ArrayList<String>();
        try {

            Connection connOne= DriverManager.getConnection(config.getJdbcUrl(), config.getUserName(), config.getPassword());

            for(String tableName:tableList){
                TableInfo tableInfo=new TableInfo();
                tableInfo.setTableName(tableName);
                tableInfo.setDescription(getTableDesc(tableName,connOne));
                List<TableColumnInfo> columnInfoList=getFieldMap(tableName,connOne);
                tableInfo.setTableColumnInfoList(columnInfoList);
                processor.process(tableInfo,this);
            }
        }catch (Exception e){
            e.printStackTrace();
            log(e.getMessage());
            log("encounter error when generate code:\n"+e.getMessage());
            return false;
        }
        return true;
    }


    public static String getTableDesc(String tableName,Connection connection) throws SQLException{
        String sql="show create table "+tableName;

        ResultSet result=doQuery(sql,connection);
        String ddl=null;
        while(result.next()) {
            ddl=result.getString("Create Table");
        }

        String comment = null;
        int index = ddl.indexOf("COMMENT='");
        if (index < 0) {
            return "";
        }
        comment = ddl.substring(index + 9);
        comment = comment.substring(0, comment.length() - 1);
        return comment;
    }

    private void getTableList(List<String> tableList,String command){
        String[] cmdArr=command.split(" ");
        for(String tableName:cmdArr){
                tableList.add(tableName.trim());
        }
    }


    public void log(final String msg) {
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                controller.log(msg);
            }
        });
    }


}
